<template>
  <div class="first-aid-container">
    <!-- 搜索和分类筛选 -->
    <div class="filter-section">
      <el-input
          v-model="searchQuery"
          placeholder="搜索急救指南"
          clearable
          style="width: 300px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select
          v-model="selectedCategory"
          placeholder="选择分类"
          clearable
          style="width: 200px; margin-left: 10px"
      >
        <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
        />
      </el-select>
    </div>

    <!-- 指南卡片列表 -->
    <div class="guide-list">
      <div v-if="loading" class="loading-message">加载中...</div>
      <el-empty v-else-if="filteredGuides.length === 0" description="暂无急救指南数据" />
    <template v-else>
      <el-card
          v-for="guide in filteredGuides"
          :key="guide.id"
          class="guide-card"
          shadow="hover"
          @click="viewGuideDetail(guide)"
      >
        <div class="card-content">
          <div class="card-header">
            <h3>{{ guide.title }}</h3>
            <el-tag :type="getSeverityTag(guide.severity)">
              {{ guide.severity }}
            </el-tag>
          </div>
          <p class="description">{{ guide.brief }}</p>
          <div class="card-footer">
            <span class="category">{{ guide.category }}</span>
            <el-button
                type="primary"
                size="small"
                @click.stop="viewGuideDetail(guide)"
            >
              查看详情
            </el-button>
          </div>
        </div>
      </el-card>
    </template>
  </div>

    <!-- 指南详情对话框 -->
    <el-dialog
        v-model="detailVisible"
        :title="currentGuide.title"
        width="70%"
        top="5vh"
    >
      <div class="guide-detail">
        <div class="severity-info">
          <span>紧急程度: </span>
          <el-tag :type="getSeverityTag(currentGuide.severity)">
            {{ currentGuide.severity }}
          </el-tag>
        </div>

        <h4>适用症状</h4>
        <p>{{ currentGuide.symptoms }}</p>

        <h4>急救步骤</h4>
        <ol class="steps">
          <li v-for="(step, index) in currentGuide.steps" :key="index">
            {{ step }}
          </li>
        </ol>

        <h4>注意事项</h4>
        <ul class="notes">
          <li v-for="(note, index) in currentGuide.notes" :key="index">
            {{ note }}
          </li>
        </ul>

        <div class="emergency-contact" v-if="currentGuide.emergencyContact">
          <h4>紧急联系方式</h4>
          <p>{{ currentGuide.emergencyContact }}</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted} from 'vue'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import {ElMessage} from "element-plus";
// 数据状态
const searchQuery = ref('')
const selectedCategory = ref('')
const detailVisible = ref(false)
const currentGuide = ref({})
const guides = ref([])
const categories = ref([])

// 严重程度标签映射
const severityMap = {
  '危急': 'danger',
  '紧急': 'warning',
  '一般': 'success'
}

// 生命周期钩子
onMounted(async () => {
  await fetchGuides()
  await fetchCategories()
})

const loading = ref(false)
// 获取指南数据
async function fetchGuides() {
  try {
    const response = await axios.get('http://localhost:6063/api/first-aid-guides')
    console.log('后端返回数据:',response.data)
    guides.value = response.data.map(guide => ({
      ...guide,
      steps: JSON.parse(guide.steps),
      notes: JSON.parse(guide.notes)
    }))
  } catch (error) {
    console.error('获取急救指南失败:', error)
    ElMessage.error('获取急救指南失败')
  }
}

// 获取分类数据
async function fetchCategories() {
  try {
    const response = await axios.get('http://localhost:6063/api/first-aid-guides/categories')
    categories.value = response.data.map(category => ({
      value: category,
      label: category
    }))
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
  }
}

// 计算属性 - 修正后的版本
const filteredGuides = computed(() => {
  return guides.value.filter(guide => {
    const matchesSearch = guide.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        guide.brief.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesCategory = !selectedCategory.value ||
        guide.category === selectedCategory.value
    return matchesSearch && matchesCategory
  })
})

// 方法
function getSeverityTag(severity) {
  return severityMap[severity] || 'info'
}

function viewGuideDetail(guide) {
  currentGuide.value = guide
  detailVisible.value = true
}

// 保存指南
async function saveGuide() {
  try {
    const guideToSave = {
      ...currentGuide.value,
      steps: JSON.stringify(currentGuide.value.steps),
      notes: JSON.stringify(currentGuide.value.notes)
    }

    const response = currentGuide.value.id
        ? await axios.put('http://localhost:6063/api/first-aid-guides', guideToSave)
        : await axios.post('http://localhost:6063/api/first-aid-guides', guideToSave)

    if (response.data) {
      ElMessage.success('保存成功')
      await fetchGuides()
      detailVisible.value = false
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 删除指南
async function deleteGuide() {
  try {
    const confirmed = await ElMessageBox.confirm(
        '确定要删除这个急救指南吗?',
        '警告',
        { type: 'warning' }
    )

    if (confirmed) {
      const response = await axios.delete(`/api/first-aid-guides/${currentGuide.value.id}`)
      if (response.data) {
        ElMessage.success('删除成功')
        await fetchGuides()
        detailVisible.value = false
      }
    }
  } catch (error) {
    console.error('删除失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style scoped>
.loading-message {
  text-align: center;
  padding: 20px;
  color: #666;
}

.first-aid-container {
  padding: 20px;
}
.filter-section {
  margin-bottom: 20px;
}
.guide-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}
.guide-card {
  cursor: pointer;
  transition: transform 0.2s;
}
.guide-card:hover {
  transform: translateY(-5px);
}
.card-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.description {
  color: #666;
  flex-grow: 1;
}
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}
.category {
  color: #888;
  font-size: 0.9em;
}
.guide-detail {
  padding: 0 10px;
}
.severity-info {
  margin-bottom: 15px;
}
.steps, .notes {
  padding-left: 20px;
  line-height: 1.8;
}
.steps {
  margin-bottom: 20px;
}
.emergency-contact {
  margin-top: 20px;
  padding: 10px;
  background-color: #fff6f6;
  border-radius: 4px;
}
</style>
